package com.qyy.springblog.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.qyy.springblog.model.Result;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@ControllerAdvice //注意加上这个注解才有效。
public class ResponseAdvice implements ResponseBodyAdvice {
    @Autowired
    private ObjectMapper objectMapper;
    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        /**
         * 设定哪些方法统一返回结果
         * 哪个接口执行统一结果返回
         */
        return true;
    }
    @SneakyThrows
    //这个注解帮我们对
    // return objectMapper.writeValueAsString(Result.success(body));
    //进行try catch。异常处理
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        //统一结果返回的具体逻辑

        if(body instanceof Result){
            return body;
        }
        //对String 类型单独处理.否则会报错
        if (body instanceof String){
            return objectMapper.writeValueAsString(Result.success(body));
        }
        return Result.success(body);
    }
}
